﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Threading;
using System.Windows.Threading;

namespace DemoApp
{
    /// <summary>
    /// Interaction logic for PopupPage.xaml
    /// </summary>
    public partial class PopupPage : Page
    {
        bool? dialogResult = null;

        public PopupPage()
        {
            InitializeComponent();
        }

        public bool? ShowDialog()
        {
            DisableMainPage();

            while (dialogPopUp.IsOpen)
            {
                // HACK: Stop the thread if the application is about to close
                if (this.Dispatcher.HasShutdownStarted ||
                    this.Dispatcher.HasShutdownFinished)
                {
                    break;
                }

                // HACK: Simulate "DoEvents"
                this.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
                Thread.Sleep(20);
            }

            return dialogResult;
        }

        private void DisableMainPage()
        {
            Application.Current.MainWindow.IsEnabled = false;
            this.Background = Brushes.LightGray;
            this.dialogPopUp.PlacementTarget = Application.Current.MainWindow;
            this.dialogPopUp.IsOpen = true;
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            dialogResult = true;
            EnableMainPage();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            dialogResult = false;
            EnableMainPage();
        }

        private void EnableMainPage()
        {
            Application.Current.MainWindow.IsEnabled = true;
            this.Background = null;
            this.dialogPopUp.PlacementTarget = Application.Current.MainWindow;
            this.dialogPopUp.IsOpen = false;
        }
    }
}
